package com.disktalk.filter;

import com.disktalk.util.DesUtil;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class CookiesFilter implements Filter {
  private final static String DES = "DES";
  private final static String key = "kxde!@#$%";//
  private final static String value = "cx";//
  @Override
  public void destroy() {

  }

  @Override
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
          throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    System.out.println("进入过滤器");
    System.out.println(request.getRequestURI());
    if (request.getRequestURI().indexOf("login")>-1||request.getRequestURI().indexOf("resources")>-1) {
      chain.doFilter(request, response);
      return;
    }
    if (request.getCookies()!=null) {
      System.out.println("过滤器读取cookie");
      Cookie[] cs = request.getCookies();
      System.out.println(cs.length);
      if (cs != null && cs.length > 0) {
        for (Cookie c : cs) {
          String cName = c.getName();
          System.out.println(cName);
          if (cName.equals("token")) {
            String token = c.getValue();
            String userAndPwd = new DesUtil().decrypt(token, key);
            String[] uNameAndPwd = userAndPwd.split(value);
            String userName = uNameAndPwd[0];
            request.getSession().setAttribute("userName", userName);
            chain.doFilter(request, response);
            return;
          }
        }
      }

    }
    System.out.println("重定向到登陆");
    response.sendRedirect("/disktalk/user/login");
  }

  @Override
  public void init(FilterConfig arg0) throws ServletException {

  }
}
